package edu.cuit.zhuyimeng.framework.workflow.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.druid.DruidDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration;
import lombok.RequiredArgsConstructor;
import org.flowable.app.spring.SpringAppEngineConfiguration;
import org.flowable.common.engine.impl.AbstractEngineConfiguration;
import org.flowable.common.engine.impl.EngineConfigurator;
import org.flowable.spring.boot.EngineConfigurationConfigurer;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;

import javax.sql.DataSource;

@AutoConfiguration(
        after = {DynamicDataSourceAutoConfiguration.class},
        before = {org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration.class}
)
@RequiredArgsConstructor
public class DataSourceAutoConfiguration implements EngineConfigurationConfigurer<SpringAppEngineConfiguration> {

    private final DataSource dataSource;

    @Override
    public void configure(SpringAppEngineConfiguration engineConfiguration) {
        engineConfiguration.addConfigurator(dataSourceEngineConfigurator());
    }

    private EngineConfigurator dataSourceEngineConfigurator() {
        return new EngineConfigurator() {
            @Override
            public void beforeInit(AbstractEngineConfiguration engineConfiguration) {
                DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) dataSource;
                engineConfiguration.setDataSource(dynamicRoutingDataSource.getDataSource("flowable"));
            }

            @Override
            public void configure(AbstractEngineConfiguration engineConfiguration) {

            }

            @Override
            public int getPriority() {
                return 1000000;
            }
        };
    }
}
